const { dbName, http } = require("../modal/db.config");
const SECRET = dbName;
const { getCurrentDateTime } = require("../modal/time.config");

const resolveDataHouseCountFun = (req, list) => {
  return new Promise(async (resolve, reject) => {
    const list = await req.services.HousesService.getList({});
    let p = list.map(async (v) => {
      v.count = await req.services.OrderService.getCount({
        where: {
          houseId: v.id,
        },
      });
      return v;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};
const resolveDataHouseSalesTotalFun = (req, list) => {
  return new Promise(async (resolve, reject) => {
    const list = await req.services.HousesService.getList({});
    let p = list.map(async (v) => {
      const data = await req.services.OrderService.getList({
        where: {
          houseId: v.id,
        },
      });
      v.salesTotal = data?.reduce((start, v) => {
        return start + v.totalPrice;
      }, 0);
      return v;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};

// 每个房屋入住分析
exports.occupancyAnalysis = async (req, res) => {
  const newData = await resolveDataHouseCountFun(req);
  if (newData) {
    res.status(200).json({ data: newData, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

// 每个房屋销售总额分析
exports.grossSales = async (req, res) => {
  const newData = await resolveDataHouseSalesTotalFun(req);
  if (newData) {
    res.status(200).json({ data: newData, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

//订单统计分析
exports.orderAnalysis = async (req, res) => {
  const list = await req.services.OrderService.getList({});
  const STATE = {
    PRE_PAY: 0, //待支付
    PAYED: 1, //已支付/审核中
    CHECK_IN: 2, //入住中
    OUT: 3, //已退租
  };
  const obj = {
    PRE_PAY: list.filter((v) => v.state === STATE.PRE_PAY).length,
    PAYED: list.filter((v) => v.state === STATE.PAYED).length,
    CHECK_IN: list.filter((v) => v.state === STATE.CHECK_IN).length,
    OUT: list.filter((v) => v.state === STATE.OUT).length,
  };
  if (list) {
    res.status(200).json({ data: obj, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};
